package com.person.jc.utils;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.plugin.activerecord.Record;
import com.person.jc.common.Constants;

@SuppressWarnings({"unchecked","rawtypes"})
public class Utils {

	public static boolean isNotEmpty(String obj) {
		return obj != null && !obj.trim().equals("") && !obj.equals("null");
	}

	public static boolean isEmpty(String obj) {
		return obj == null || obj.equals("") || obj.equals("null");
	}
	
	/**
	 * 
	 * @Description: [将空对象转化为空字符串]
	 * @Author: 武智雄 (491933243@qq.com)
	 * @Date: 2014-3-15
	 * @@param str
	 * @@return
	 */
	public static String convertNullToEmpty(String str) {
		return isEmpty(str) ? "" : str;
	}
	
	/**
	 * 
	 * @Description: [将空字符串转化为空对象]
	 * @Author: 武智雄 (491933243@qq.com)
	 * @Date: 2014-3-15
	 * @@param str
	 * @@return
	 */
	public static Object convertEmptyToNull(String str) {
        return isEmpty(str) ? null : str;
    }
	
	/**
	 * 
	 * @Description: [字符串如果为空的话转化为自定义字符]
	 * @Author: 武智雄 (491933243@qq.com)
	 * @Date: 2014-3-19
	 * @@param oldStr
	 * @@param newStr
	 * @@return
	 */
	public static String convertNullToStr(Object oldStr,String newStr) {
        return isEmpty(String.valueOf(oldStr)) ? newStr : String.valueOf(oldStr);
    }

	/**
	 * 替换字符串msgtext当中的由{}指示的部分内容，返回完整的字符串
	 * 
	 * @param msgtext
	 * @param params
	 * @return
	 */
	public static String substituteParams(String msgtext, Object params[]) {
		Locale locale = Locale.CHINESE;
		String localizedStr = null;
		if (params == null || msgtext == null) {
			return msgtext;
		}
		StringBuffer b = new StringBuffer(100);
		MessageFormat mf = new MessageFormat(msgtext);
		if (locale != null) {
			mf.setLocale(locale);
			b.append(mf.format(params));
			localizedStr = b.toString();
		}
		return localizedStr;
	}

	public static Double changeLongToDouble(long longView) {
		String doubleStr = Long.toString(longView);
		return new Double(doubleStr);
	}

	public static boolean contrastTime(Date contrastTime, Date nowTime,
			int dayCount) {
		boolean result = false;
		long dayCountTime = dayCount * 24 * 60 * 60 * 1000;
		if (nowTime.getTime() - contrastTime.getTime() > dayCountTime) {
			result = true;
		}
		return result;
	}

	public static String toGBK(String uniStr) {
		String gbStr = "";
		if (uniStr == null) {
			uniStr = "";
		}
		try {
			byte[] tempByte = uniStr.getBytes("ISO8859_1");
			gbStr = new String(tempByte, "GB2312");
		} catch (Exception ex) {
		}
		return gbStr;
	}

	//
	public static String toUni(String gbStr) {
		String uniStr = "";
		if (gbStr == null) {
			gbStr = "";
		}
		try {
			byte[] tempByte = gbStr.getBytes("GB2312");
			uniStr = new String(tempByte, "ISO8859_1");
		} catch (Exception ex) {
		}
		return uniStr;
	}

	public static String LongTo2str(Long value) {
		BigInteger src = new BigInteger(value.toString());// 转换为BigInteger类型
		return src.toString(2);
	}

	public static Long str2ToLong(String value) {
		BigInteger src = new BigInteger(value, 2);// 转换为BigInteger类型
		return new Long(src.toString());
	}

	public static String stringTo8str2(String value) {
		BigInteger src = new BigInteger(value);
		String str2 = src.toString(2);
		while (str2.length() < 8) {
			str2 = "0" + str2;
		}
		return str2;
	}

	/**
	 * 
	 * @Description: [把单引号转义为双单引号]
	 * @Author: 武智雄 (491933243@qq.com)
	 * @Date: Jul 1, 2011
	 * @@param inStr
	 * @@return
	 */
	public static String escapeSingleQuotes(String inStr) {
		if (Utils.isNotEmpty(inStr)) {
			inStr = inStr.replace("'", "''");
			inStr = inStr.replace("\\", "\\\\");
			return inStr.trim();
		}else{
			return inStr;
		}
	}

	/**
	 * 中文符号转换为英文
	 */
	public static String conversionCHToEN(String s) {
		s = s.replace("／", "/");
		s = s.replace("—", "-");
		s = s.replace("。", ".");
		s = s.replace("（", "(");
		s = s.replace("）", ")");
		s = s.replace("？", "?");
		s = s.replace("；", ";");
		s = s.replace("：", ":");
		return s;
	}

	/**
	 * 截取字符串，显示.. flag 0-中间变.. 1-后边变.. number 前边显示几位
	 */
	public static String subString(String s, int flag, int number) {
		if (flag == 0) {
			if (s.length() > number) {
				return s.substring(0, number) + ".."
						+ s.substring(s.length() - 1, s.length());
			} else {
				return s;
			}
		} else {
			if (s.length() > number) {
				return s.substring(0, number) + "..";
			} else {
				return s;
			}
		}
	}

	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("PRoxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static String getSqlIds(String str){
		String ids = str.substring(0,str.length()-1);
		ids = "'"+ids+"'";
		ids = ids.replace(",","','");
		return ids;
	}

    public static String getSelect(List list,String defText,boolean ifTree,boolean ifTag){
	    List newList = new ArrayList();
	    if (Utils.isNotEmpty(defText)) {
            Map<String, String> noMap = new HashMap<String,String>();;
            if(ifTree){
                noMap.put("id", "");
                noMap.put("text", defText);
                noMap.put("iconCls", "icon-white");
            }else{
                noMap.put(Constants.defSelectKey, "");
                noMap.put(Constants.defSelectText, defText);
            }
            newList.add(0, noMap);
        }
	    
	    if (list != null && list.size() > 0) {
    	    if(ifTree){
                Map<String, String> tempMap = (Map<String, String>) list.get(0);
                String key = tempMap.get(Constants.defSelectKey);
                //普通list计划
//                if("id".equals(key.toLowerCase()))
//                    key = tempMap.get(key);
                
                String[] keys = key.split(",");
                newList.addAll(getTree(list,keys[1],"1",null));
            }else{
                newList.addAll(list);
            }
	    }
        
        String returnStr = "";
        if (newList.size() > 0) {
        	JsonMapper json =  JsonMapper.nonDefaultMapper();
        	returnStr = json.toJson(newList);
            returnStr = returnStr.replaceAll("null", "\"\"");
            if(ifTag)
                returnStr = returnStr.replaceAll("\"",
                "'").replaceAll("'id'", "id").replaceAll("'text'", "text")
                .replaceAll("'iconCls'", "iconCls").replaceAll("'checked'",
                        "checked");
        }else{
            returnStr = "[]";
        }
        
        return returnStr;
	}
	
    public static List getTree(List<Map<String, String>> codeList,String pid,String flag,List pidList){
        List newList1 = new ArrayList();
        if(pidList == null){
        	pidList = new ArrayList();
        }
        pidList.add(pid);//添加父ID
        for (Map<String, String> tempMap1 : codeList) {
            String key1 = tempMap1.get(Constants.defSelectKey);
            String value1 = tempMap1.get(Constants.defSelectText);
            //普通list计划
//            if("id".equals(key1.toLowerCase())){
//                key1 = tempMap1.get(key1);
//                value1 = tempMap1.get("TEXT");
//            }else{//自定义标签中封装list
//                value1 = tempMap1.get(key1);
//            }
            String[] keys1 = key1.split(",");
            if(keys1[1].equals(pid)){
                Map newMap1 = new HashMap();
                newMap1.put("id", keys1[0]);
                newMap1.put("text", value1);
                newMap1.put("iconCls", "icon-dept");
                if(keys1.length > 2){
                    if(Utils.isNotEmpty(keys1[2])){
                        newMap1.put("checked", true);
                    }
                }
//                if(Integer.parseInt(keys1[2]) > 0){
                    List newList2 = getTree(codeList,keys1[0],"",pidList);
                    if(newList2.size() > 0){
                        newMap1.put("state", "closed");
                        newMap1.put("children", newList2);
                    }
//                }
                
                newList1.add(newMap1);
            }else{
            	if(Utils.isNotEmpty(flag)){
            		if(!pidList.contains(keys1[1])){
            			Map newMap1 = new HashMap();
            			newMap1.put("id", keys1[0]);
            			newMap1.put("text", value1);
            			newMap1.put("iconCls", "icon-dept");
            			newList1.add(newMap1);
            		}
            	}
            }
        }
        return newList1;
    }
	
    public static List<Record> getSelect(List<Record> list,boolean ifTree){
	    List<Record> newList = new ArrayList<Record>();
	    if (list != null && list.size() > 0) {
            if(ifTree){
                Record tempMap =  list.get(0);
                String key = tempMap.get(Constants.defSelectKey);
                
                String[] keys = key.split(",");
                Record newMap1 = new Record();
                newMap1.set(Constants.defSelectKey, keys[0]);
                newMap1.set(Constants.defSelectText, tempMap.get(Constants.defSelectText));
                newList.add(newMap1);
                String pid = "";
                if(keys.length > 1)
                    pid = keys[1];
                newList = getSelectTree(list, pid, 1);
                
                //如果没有关联到上下级关系，默认添加到最后
                if(list.size() != newList.size()){
                    List<Record> newList2 = new ArrayList<Record>();
                    for(int i = 0;i < list.size(); i++){
                        Map<String, String> map = (Map<String, String>) list.get(i);
                        String key_ = map.get(Constants.defSelectKey);
                        
                        String[] keys_ = key_.split(",");
                        boolean ifExits = false;
                        for(Record valMap:newList){
                            if(keys_[0].equals(String.valueOf(valMap.get(Constants.defSelectKey)))){
                                ifExits = true;
                                break;
                            }
                        }
                        if(!ifExits){
                            Record newMap1_ = new Record();
                            newMap1_.set(Constants.defSelectKey, keys_[0]);
                            newMap1_.set(Constants.defSelectText, map.get(Constants.defSelectText));
                            
                            newList2.add(newMap1_);
                        }
                    }
                    
                    newList.addAll(newList2);
                }
            }else{
                newList = list;
            }
        }
	    
	    return newList;
	}
	
    public static String getSelectJson(List list,boolean ifTree){
	    String result = "";
	    List resultList = getSelect(list,ifTree);
        if (resultList.size() > 0) {
        	JsonMapper json =  JsonMapper.nonDefaultMapper();
            result = json.toJson(resultList);
            result = result.replaceAll("null", "\"\"");
        }else{
            result = "[]";
        }
        
        return result;
	}
	
    public static List<Record> getSelectTree(List<Record> codeList,String pid,int lvl){
	    List<Record> newList1 = new ArrayList<Record>();
        
	    for (Record tempMap1 : codeList) {
            String key1 = tempMap1.get(Constants.defSelectKey);
            String value1 = tempMap1.get(Constants.defSelectText);
            
            Record tempMap = new Record();
            tempMap.set(Constants.defSelectText, value1);
            
            String[] keys1 = key1.split(",");
            String tempPid = "";
            if(keys1.length > 1)
                tempPid = keys1[1];
            if(tempPid.equals(pid)){
                if(lvl > 1)
                    //tempMap.put(Constants.defSelectText, leftPadStr("└-" + value1, lvl - 1, "　"));
                	tempMap.set(Constants.defSelectText, leftPadStr(value1, lvl - 1, "　"));
                
                tempMap.set(Constants.defSelectKey, keys1[0]);
                newList1.add(tempMap);
                newList1.addAll(getSelectTree(codeList, keys1[0], lvl+1));
            }
	    }
	    return newList1;
	}
	
	/**
	 * 
	 * @Description: [左边添加字符]
	 * @Author: 武智雄 (wuzhixiong@vvise.com)
	 * @Date: 2014-11-25
	 * @@param str
	 * @@param size
	 * @@param padStr
	 * @@return
	 */
	public static String leftPadStr(String str, int size, String padStr){
	    String temp = "";
	    for(int i = 0;i < size; i++)
	        temp += padStr;
	    return temp += str;
	}
	
	/**
	 * 
	 * @Description: [将,拼接的普通字符串转化为sql中in or not in使用]
	 * @Author: 武智雄 (wuzhixiong@vvise.com)
	 * @Date: 2014-12-11
	 * @@param source
	 * @@return
	 */
	public static String getInSplit(String source){
	    if(source.startsWith(","))
	        source = source.substring(1);
	    if(source.endsWith(","))
	        source = source.substring(0, source.length() - 1);
	    
	    return "'" + source.replaceAll(",", "','") + "'";
	}
	
	/**
	 * 
	 * @Description: [将,拼接的普通字符串转化为sql中in or not in使用,1000条添加一次or]
	 * @Author: 武智雄 (wuzhixiong@vvise.com)
	 * @Date: 2014-12-22
	 * @@param source
	 * @@param columnName 使用in字段名，包含表别名（如：t.order_id）
	 * @@param inWhere in or ont in
	 * @@return
	 */
	public static String getInSplit(String source,String columnName,String inWhere){
	    String[] sources = source.split(",");
	    StringBuffer result = new StringBuffer("");
	    String andWhere = "and";
	    if("in".equals(inWhere))
	        andWhere = "or";
	    int i = 0;
	    for(String str : sources){
	        if(i % 1000 == 0 && i != 0){
	            result.append( ") "+ andWhere +" " + columnName + " "+ inWhere +" ( ");
	        }else{
	            if(i > 0)
	                result.append( ",");
	        }
	        result.append("'" + str + "'");
	        i++;
	    }
	    
	    return result.toString();
	}
	
	/**
	 * 
	 * @Description: [将,拼接的普通字符串转化为sql中in使用,1000条添加一次or]
	 * @Author: 武智雄 (wuzhixiong@vvise.com)
	 * @Date: 2014-12-22
	 * @@param source
	 * @@param columnName
	 * @@return
	 */
	public static String getInSplit(String source,String columnName){
	    return getInSplit(source, columnName, "in");
	}
	
	/**
     * 
     * @Description: [获取执行数据库参数]
     * @Author: 武智雄 (wuzhixiong@vvise.com)
     * @Date: Nov 27, 2015
     * @@param list
     * @@return
     */
    public static Object[] getObjParam(List<Object> params){
        Object[] obj = new Object[params.size()];
        int i = 0;
        for(Object param : params){
            obj[i] = param;
            i++;
        }
        
        return obj;
    }
    
    public static Object[] getObjParam(Object o){
        return getObjParam((List<Object>) o);
    }
    
    /**
     * 将数组转成字符串，以逗号隔开
     * @作者 : 王春林（chunlin.wang@51durian.com）
     * @日期 : 2017年1月14日
     * @param arr
     * @return
     */
    public static String toString(String[] arr){
    	String resultStr = "";
    	if(arr!=null && arr.length>0){
    		for (int i = 0; i < arr.length; i++) {
				if(!"".equals(resultStr))
					resultStr += ",";
				resultStr += arr[i];
			}
    	}
    	return resultStr;
    }
}